from django.shortcuts import render, render_to_response
from django import forms
from django.http import HttpResponse
from PIL import Image
# Create your views here.
class UserForm(forms.Form):
    charset = forms.CharField()
    size = forms.IntegerField(max_value=100, min_value=1)
    img = forms.FileField()



def make_char_img(imgfile_name, color='MNHQ$OC?7>!:-:.'):
    img = Image.open(imgfile_name)
    resize_img = img.resize((64, 32), Image.ANTIALIAS)
    resize_img = resize_img.convert("L")
    pixel = resize_img.load()
    picture_str = ""
    width, height = resize_img.size
    for h in range(0, height):
        for w in range(0, width):
            #print(pixel[w, h])
            picture_str += color[int(pixel[w, h] * 14 /255)]
        picture_str += '\n'
    return picture_str

def index(request):
    if request.method == 'POST':
        uf = UserForm(request.POST, request.FILES)
        if uf.is_valid() or len(uf.cleaned_data['charset']) != 16:
            # 获取表单信息
            img = uf.cleaned_data['img']
            color = uf.cleaned_data['charset']
            size = uf.cleaned_data['size']
            image = Image.open(img)
            image_date = image.load()
            text = make_char_img(img, color)
            return render_to_response('text_img.html', {'source_text': text, 'size': size})
        else:
            return HttpResponse("sorry, the uf is not valid")
    else:
        uf = UserForm()
    return render_to_response('index.html', {'uf': uf})
